package com.dp.appi.util;

import com.dp.appi.exception.CommonException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class SendSMS {

    /** 言味平台发送短信 **/
    public  boolean send(String mob, String valicode) {
        String str = "";
        String msg = "您本次操作的验证码是："+valicode+"，请核对并确认是否是本人操作。【设计通】";
        try {
            // 创建HttpClient实例
            HttpClient httpclient =new DefaultHttpClient();

            //构造一个post对象
            HttpPost httpPost = new HttpPost("http://h.1069106.com:1210/Services/MsgSend.asmx/SendMsg");
            //添加所需要的post内容
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("userCode", "LKSDK0005738"));
            nvps.add(new BasicNameValuePair("userPass", "dlpwsj@lk"));
            nvps.add(new BasicNameValuePair("DesNo", mob));
            nvps.add(new BasicNameValuePair("Msg", msg));
            nvps.add(new BasicNameValuePair("Channel", "0"));


            httpPost.setEntity( new UrlEncodedFormEntity(nvps, "UTF-8") );
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                str = convertStreamToString(instreams);
                System.out.println(str);
            }

//        	HttpRequestSender httpRequest = new HttpRequestSender();
//        	//发送 POST 请求
//        	 String sr=WeixinUtil.httpRequest(
//        			 "http://h.1069106.com:1210/Services/MsgSend.asmx/SendMsg",
//        			 "POST",
//             		 "userCode=XXXXX&userPass=XXXXX&DesNo="+mob+"&Msg="+msg+"&Channel=1");

            Document doc = null;
            doc = DocumentHelper.parseText(str); // 将字符串转为XML

            if (doc == null ) return false;
            Element rootElt = doc.getRootElement(); // 获取根节点
            if (rootElt == null ) return false;
            //System.out.println("根节点：" + rootElt.getName()); // 拿到根节点的名称
            System.out.println("根节点的值：" + rootElt.getText()); // 拿到根节点的名称
            if (rootElt.getText() == null || "".equals(rootElt.getText())) return false;
            if (Long.parseLong(rootElt.getText()) > 0 ) {
                return true;
            } else {
                return false;
            }

        } catch (DocumentException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /*
         * 发送方法
         * 凌凯短信接口
         */
    public static boolean sendSMS(String Mobile, String valicode,Long send_time,int templet) throws MalformedURLException, UnsupportedEncodingException {
        URL url = null;
        String[] ContentArr = {
                "您的注册验证码"+valicode+"（5分钟内有效）【设计通】",
                "您正在重置密码，验证码"+valicode+"（5分钟内有效）【设计通】"
        };
        String CorpID="LKSDK0005738";//账户名
        String Pwd="dlpwsj@lk";//密码
        String send_content= URLEncoder.encode(ContentArr[templet].replaceAll("<br/>", " "), "GBK");//发送内容
        url = new URL("http://mb345.com:999/ws/BatchSend2.aspx?CorpID="+CorpID+"&Pwd="+Pwd+"&Mobile="+Mobile+"&Content="+send_content+"&cell=&SendTime="+(send_time==null?"":send_time));
        BufferedReader in = null;
        int inputLine = 0;
        try {
            System.out.println("开始发送短信手机号码为 ："+Mobile);
            in = new BufferedReader(new InputStreamReader(url.openStream()));
            inputLine = new Integer(in.readLine()).intValue();
        } catch (Exception e) {
            throw new CommonException("L10006");
        }
        return inputLine>0?true:false;
    }


    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }


}
